package com.jrx.anytxn.transaction.job.customer.step;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.JsonUtils;
import com.jrx.anytxn.customer.entity.CmCustomerLimitInfo;
import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
import com.jrx.anytxn.customer.entity.CmLimitChangeLog;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerSecondLevelMapper;
import com.jrx.anytxn.customer.service.ICustomerLimitInfoService;
import com.jrx.anytxn.feign.api.request.LimitRenewOperateReq;
import com.jrx.anytxn.feign.api.response.LimitRenewResponse;
import com.jrx.anytxn.feign.api.service.IUserApiService;
import com.jrx.anytxn.feign.gateway.bean.ApiResponse;
import com.jrx.anytxn.param.entity.PrCodeTable;
import com.jrx.anytxn.param.entity.PrCreditLimitMapping;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtPrCodeTableMapper;
import com.jrx.anytxn.param.mapper.ext.ExtPrCreditLimitMappingMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.dto.common.SendSmsReq;
import com.jrx.anytxn.transaction.entity.AmLoanMainInfoVo;
import com.jrx.anytxn.transaction.mapper.ext.ExtAmLoanMainInfoMapper;
import com.jrx.anytxn.transaction.service.ISmsService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @comment: 额度续期短信Processor
 * @author: liuzb
 * @date: 2022/10/19 10:00
 */
@Service
public class LimitRenewalSmsProcessor implements ItemProcessor<CmCustomerLimitInfo, CmCustomerLimitInfo> {

    private static final Logger logger = LoggerFactory.getLogger(LimitRenewalSmsProcessor.class);

    @Autowired
    private IUserApiService iUserApiService;
    @Resource
    private ExtPrCreditLimitMappingMapper extPrCreditLimitMappingMapper;
    @Resource
    private ExtCmCustomerSecondLevelMapper extCmCustomerSecondLevelMapper;
    @Resource
    private ExtPrCodeTableMapper extPrCodeTableMapper;
    @Resource
    private ISmsService iSmsService;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private ExtAmLoanMainInfoMapper extAmLoanMainInfoMapper;
    @Resource
    private ICustomerLimitInfoService iCustomerLimitInfoService;

    @Override
    public CmCustomerLimitInfo process(CmCustomerLimitInfo customerLimit) throws Exception {

        String organizationId = customerLimit.getOrganizationId();
        String channel = customerLimit.getChannel();
        String tenantId = customerLimit.getTenantId();
        String limitId = customerLimit.getLimitId();
        String customerId = customerLimit.getCustomerId();
        Date limitExpiryDate = customerLimit.getLimitExpiryDate();
        String expiryDate = DateUtils.format(limitExpiryDate);
        String productId = "";
        List<PrCreditLimitMapping> mappings = extPrCreditLimitMappingMapper.selectLimitListIdAndTenantId(organizationId, channel, tenantId, limitId);
        if (CollectionUtils.isNotEmpty(mappings)) {
            Optional<PrCreditLimitMapping> min = mappings.stream().min(Comparator.comparing(PrCreditLimitMapping::getProductId));
            if (min.isPresent()) {
                productId = min.get().getProductId();
            }
        }
        if (StringUtils.isBlank(productId)) {
            logger.warn("客户id：{},额度id：{}没有对应的产品编号", customerId, limitId);
            return null;
        }
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        // 当前业务日期
        Date today = org.getNextProcessingDate();
        // 原产品额度到期前没有用信的用户不发短信
        // 获取用户"首笔贷款额度信息"
        CmLimitChangeLog firstLimitInfo = iCustomerLimitInfoService.queryFirstLimitChangeLog(tenantId, customerId, Collections.singletonList(productId));

        if(today.compareTo(limitExpiryDate) <= 0 && (Objects.isNull(firstLimitInfo) || StringUtils.isBlank(firstLimitInfo.getEtlLoanId()))){
            logger.info("该用户{}额度到期前没有用信记录，不必发送短信", customerId);
            return null;
        }
        logger.info("客户id：{},产品编号：{},额度有效期：{}", customerId, productId, expiryDate);
        CmCustomerSecondLevel secondLevel = extCmCustomerSecondLevelMapper.selectByCustomerIdAndChannel(customerId, channel, tenantId);
        LimitRenewOperateReq limitReq = new LimitRenewOperateReq();
        limitReq.setProductId(productId);
        limitReq.setChannelNo(customerLimit.getChannel());
        limitReq.setUserId(secondLevel.getUserId());
        limitReq.setTenantId(tenantId);
        ApiResponse<LimitRenewResponse> limitRenewQueryRes = null;
        try {
            limitRenewQueryRes = iUserApiService.limitRenewQuery(JsonUtils.toJSon(limitReq));
        } catch (Exception e) {
            e.printStackTrace();
            logger.warn("额度续签查询API失原因", e);
        }
        if (limitRenewQueryRes == null || TxnRespCode.SUCCESS.getCode() != limitRenewQueryRes.getCode()) {
            logger.warn("额度续签查询API失败,响应为空或者非成功码值");
        }
        // 风控返回的续签状态 0：额度不可续签，1：可续期
        String renewType = "0";
        if (Objects.nonNull(limitRenewQueryRes) && Objects.nonNull(limitRenewQueryRes.getData()) && StringUtils.isNotBlank(limitRenewQueryRes.getData().getRenewType())) {
            renewType = limitRenewQueryRes.getData().getRenewType();
        }
        String smsType;
        // 到期前
        if (today.compareTo(limitExpiryDate) <= 0) {
            //可续期
            if ("1".equalsIgnoreCase(renewType)) {
                smsType = TransBizConstant.SMS_TYPE_BEFORE_RENEWAL;
            } else {
                // 不可续期
                smsType = TransBizConstant.SMS_TYPE_BEFORE_NOT_RENEWAL;
            }
        } else {
            // 到期后
            //可续期
            if ("1".equalsIgnoreCase(renewType)) {
                // 查询是否用信
                List<AmLoanMainInfoVo> list = extAmLoanMainInfoMapper.selectLoanInfoGroupByDay(tenantId, customerId);
                // 已用信
                if (CollectionUtils.isNotEmpty(list)) {
                    smsType = TransBizConstant.SMS_TYPE_AFTER_RENEWAL;
                } else {
                    // 未用信
                    smsType = TransBizConstant.SMS_TYPE_AFTER_UNUSED_RENEWAL;
                }
            } else {
                // 不可续期
                smsType = TransBizConstant.SMS_TYPE_AFTER_NOT_RENEWAL;
            }
        }
        PrCodeTable prCodeTables = extPrCodeTableMapper.selectByTypeIdAndCodeId("SEND_DAY", smsType, tenantId);
        if (Objects.nonNull(prCodeTables)) {
            String[] days = prCodeTables.getCodeDescription().split(",");
            for (int i = 0; i < days.length; i++) {
                int day = Integer.parseInt(days[i]);
                // 是否满足发送短信的条件
                if (DateUtils.addDay(today, day).compareTo(limitExpiryDate) == 0) {
                    SendSmsReq req = new SendSmsReq();
                    logger.info("----额度续期短信组装参数中----");
                    //生成流水号
                    req.setChannel(secondLevel.getChannel());
                    req.setTenantId(secondLevel.getTenantId());
                    // 身份证有效期短信
                    req.setSmsType(smsType);
                    String seqNo = (int) (Math.random() * 100000) + System.currentTimeMillis() + "";
                    req.setSeqNo(seqNo);
                    String mobile = secondLevel.getMobile();
                    req.setMobile(mobile);
                    req.setCustomerId(customerId);
                    // 额度有效期
                    req.setExpireDate(expiryDate);
                    try {
                        iSmsService.sendSmsMq(req);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    logger.info("发送成功{}", secondLevel.getCustomerId());
                    break;
                }
            }
        }
        return customerLimit;
    }
}
